package com.example.dense_rack_server.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.dense_rack_server.entity.MyUser;
import com.example.dense_rack_server.entityVo.MyUserVo;
import com.example.dense_rack_server.security.dto.JwtUserDto;
import com.example.dense_rack_server.service.MyUserService;
import com.example.dense_rack_server.utils.ResponseModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author  张彬 
 * @since 2025-03-03
 */
@Controller
@RequestMapping("/my/user")
public class MyUserController {
    @Resource
    private MyUserService myUserService;

    @GetMapping("/index/view")
    public String indexView() {
        return "user/table-list";
    }

    /**
     * 绘制部门树结构
     */
    @GetMapping("/buildDept")
    @ApiOperation("绘制部门树结构")
    @ResponseBody
    public Map<String, Object> buildDept() {
        return myUserService.buildDept();
    }

    @ResponseBody
    @GetMapping("/list")
    public Map<String, Object> userList(@RequestParam(value = "user_name", required = false) String user_name,
                                        @RequestParam(value = "nick_name", required = false) String nick_name,
                                        @RequestParam(value = "deptId", required = false) String deptId,
                                        @RequestParam(value = "status", required = false) String status,
                                        @RequestParam(value = "page") int page,
                                        @RequestParam(value = "limit") int limit) {
        return myUserService.userList(user_name, nick_name, deptId, status, page, limit);
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    @ApiOperation("新增用户")
    public ModelAndView add() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("user/user_add");
        return modelAndView;
    }

    /**
     * 新增用户保存
     *
     * @param myUserVo
     * @return
     */
    @PostMapping("/save")
    @ResponseBody
    public ResponseModel save(@RequestBody MyUserVo myUserVo) {
        if (StrUtil.isEmpty(myUserVo.getUserName()) || StrUtil.isEmpty(myUserVo.getPassword())) {
            return ResponseModel.fail("用户名和密码参数缺少");
        }
        MyUser myUser = myUserService.getOne(new QueryWrapper<MyUser>().eq("user_name", myUserVo.getUserName()));
        if (myUser != null) {
            return ResponseModel.fail("用户已存在,无法创建");
        }
        if (StrUtil.isNotEmpty(myUserVo.getPassword())) {
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            myUserVo.setPassword(bCryptPasswordEncoder.encode(myUserVo.getPassword()));
        }
        return myUserService.saveUser(myUserVo);
    }

    /**
     * 修改用户页面
     *
     * @param userId
     * @return
     */
    @GetMapping("/edit")
    public ModelAndView edit(@RequestParam String userId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("user/user_edit");
        modelAndView.addObject("user", myUserService.getById(userId));
        return modelAndView;
    }

    /**
     * 修改用户数据
     *
     * @param user
     * @return
     */
    @PostMapping("/edit")
    @ResponseBody
    public ResponseModel edit(@RequestBody JSONObject user) {
        return myUserService.editUser(user);
    }

    /**
     * 修改状态
     *
     * @param data
     * @return
     */
    @PutMapping("/changeStatus")
    @ResponseBody
    public ResponseModel changeStatus(@RequestBody JSONObject data) {
        return myUserService.changeStatus(data);
    }


    /**
     * 删除用户
     *
     * @param user_id
     * @return
     */
    @DeleteMapping("/delete/{user_id}")
    @ResponseBody
    public ResponseModel delete(@PathVariable("user_id") String user_id) {
        return myUserService.deleteUser(user_id);
    }


    /**
     * 用户详情
     */
    @GetMapping("/detail/{user_id}")
    public ModelAndView userDetail(@PathVariable("user_id") String user_id) {
        return myUserService.userDetail(user_id);
    }


    // 修改密码
    @GetMapping("/changePwd")
    public ModelAndView changePwd() {
        return myUserService.changePwd();
    }

    @ResponseBody
    @ApiOperation("修改密码")
    @PostMapping(value = "/change/pwd")
    public ResponseModel changePwd(@RequestBody JSONObject data) {
        if (StrUtil.isEmpty(data.getStr("usedPwd")) || StrUtil.isEmpty(data.getStr("newPwd"))) {
            return ResponseModel.fail("缺少参数");
        }
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        int userId = jwtUserDto.getMyUser().getUserId();
        MyUser myUser = myUserService.getById(userId);
        // 效验旧密码
        if (!new BCryptPasswordEncoder().matches(data.getStr("usedPwd"), myUser.getPassword())) {
            return ResponseModel.fail("抱歉,你输入的旧密码错误,无法执行修改操作");
        }
        // 新密码写入到数据库
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String passHash = bCryptPasswordEncoder.encode(data.getStr("newPwd"));
        MyUser updateUser = new MyUser();
        updateUser.setPassword(passHash);
        updateUser.setUserId(myUser.getUserId());
        boolean updateStatus = myUserService.updateById(updateUser);
        return updateStatus ? ResponseModel.success("修改密码成功") : ResponseModel.fail("修改密码失败");
    }
}
